<?php
/**
 * Date: 2021/6/25/025 16:10
 * For: 微信小程序开发sdk类
 */

namespace wehcat;


use wehcat\lib\WXBizDataCrypt;

class WechatApp
{

    /**
     * 获取openid
     * @param $appid
     * @param $secret
     * @param $code
     * @return bool|mixed|string
     */
    public function openId($appid,$secret,$code){
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$secret."&js_code=".$code."&grant_type=authorization_code";
        $data = $this->request_get($url);
        if ($data) {
            $data = json_decode($data,true);
        }
        return $data;
    }

    /**
     * 获取手机号
     * @param $appid
     * @param $iv
     * @param $encryptedData
     * @param $sessionKey
     * @return mixed
     */
    public function getPhoneNumber($appid,$iv,$encryptedData,$sessionKey){
        $pc = new WXBizDataCrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data );
        if ($errCode == 0) {
            $data = json_decode($data);
        }
        return $data;
    }


    /**
     * curl请求
     * @param string $url
     * @return bool|string
     */
    function request_get($url = ''){
        if (empty($url)) {
            return false;
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 500);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
}